//
//  JBSStopMainViewController.m
//  changwonbus
//
//  Created by park juram on 12. 11. 20..
//  Copyright (c) 2012년 park juram. All rights reserved.
//

#import "JBSStopMainViewController.h"
#import "JBSBusStopMainTableViewCell.h"
#import "JBSBusStopDetailViewController.h"
#import "HttpRequest.h"
#import "HTMLParser.h"
#import "HTMLNode.h"

@interface JBSStopMainViewController ()

@end

@implementation JBSStopMainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [_searchBar setShowsCancelButton:YES animated:YES];
    return true;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    [_searchBar setShowsCancelButton:NO animated:YES];
    return true;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [_searchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if(_dataArray == nil)
    {
        _dataArray = [[NSMutableArray alloc] init];
    }
    [_dataArray removeAllObjects];
    
    NSString *url = @"http://bus.changwon.go.kr/busInfo/busInfoDetail.jsp";
    
    // HTTP Request 인스턴스 생성
    HttpRequest *httpRequest = [[HttpRequest alloc] init];
    
    // POST로 전송할 데이터 설정
    NSDictionary *bodyObject = [NSDictionary dictionaryWithObjectsAndKeys:
								@"1", @"ra_type",
								[_searchBar text], @"search_title",
								nil];
	//NSString *bodyObject = @"type=getUser&seq=1&latitude=38.0&longitude=127.0&time=13600&unit='k'&distance=9999";
    
    // 통신 완료 후 호출할 델리게이트 셀렉터 설정
    [httpRequest setDelegate:self selector:@selector(didReceiveFinished:)];
    
    // 페이지 호출
    [httpRequest requestUrl:url bodyObject:bodyObject];

}
-(void)didReceiveFinished:(NSString *)receiveString
{
    HTMLParser *parser = [[HTMLParser alloc]
                          initWithString:receiveString error:nil];
    
//    NSLog( @"%@", receiveString );
    
    HTMLNode *bodyNode = [parser body];
    NSArray *searchResult = [[[bodyNode findChildOfClass:@"search_result2"] findChildOfClass:@"scroll"] findChildTags:@"tr"];
    
    for ( int i=0; i<[searchResult count]; i++ ) {
        HTMLNode *busStopNumberNode = [[searchResult objectAtIndex:i] findChildTag:@"strong"];
        HTMLNode *busStopNameNode = [[searchResult objectAtIndex:i] findChildWithAttribute:@"width" matchingName:@"120" allowPartial:YES];
        
        NSString *busStopNumber = [busStopNumberNode contents];
        NSString *busStopName = [busStopNameNode contents];
        NSString *busStopId = [[[searchResult objectAtIndex:i] findChildTag:@"a"] getAttributeNamed:@"onclick"];
        
        NSRange startPos = [busStopId rangeOfString:@"'"];
        NSRange endPos = [busStopId rangeOfString:@"'" options:NSBackwardsSearch];
        startPos.location += 1;
        
        startPos.length = endPos.location - startPos.location;
        busStopId = [busStopId substringWithRange:startPos];
        NSDictionary *data = [[NSDictionary alloc]initWithObjectsAndKeys:busStopNumber, @"busStopNumber", busStopName, @"busStopName", busStopId, @"busStopId", nil];
        [_dataArray addObject:data];
 
    };
    [_busStopTableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationFade];
}
#pragma mark -
-(void)viewWillAppear:(BOOL)animated
{

}
-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"BusStopMainTableCell";
    static BOOL nibsRegistered = NO;
    if ( !nibsRegistered ) {
        UINib *nib = [UINib nibWithNibName:@"BusStopMainTableCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:cellIdentifier];
        nibsRegistered = YES;
    }
    
    JBSBusStopMainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    NSInteger row = [indexPath row];
    NSDictionary *rowData = [_dataArray objectAtIndex:row];
    
    [cell.busStopName setText:[rowData objectForKey:@"busStopName"]];
    NSString *numberStr = [[NSString alloc]initWithFormat:@"(%@)", [rowData objectForKey:@"busStopNumber"] ];
    [cell.busStopNumber setText:numberStr];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    [_searchBar resignFirstResponder];
    [self performSegueWithIdentifier: @"busStopDetail" sender: self];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"busStopDetail"]) {
        NSIndexPath *indexPath = [_busStopTableView indexPathForSelectedRow];
        NSInteger row = [indexPath row];
        NSDictionary *rowData = [_dataArray objectAtIndex:row];
        
        JBSBusStopDetailViewController *destViewController = segue.destinationViewController;
        destViewController.busStopId = [[NSString alloc]initWithFormat:@"%@", [rowData objectForKey:@"busStopId"]];
        destViewController.busStopName = [[NSString alloc]initWithFormat:@"%@", [rowData objectForKey:@"busStopName"]];
        destViewController.busStopNumber = [[NSString alloc]initWithFormat:@"%@", [rowData objectForKey:@"busStopNumber"]];

    }
}

@end
